/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: serialstd_linux.cpp,v 1.9 2009-05-13 07:18:13 amaula Exp $
 *
 * \file
 * \brief ASRoboBus interface compatible Serial port implementation for Linux.
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/uio.h>
//#include <sys/io.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <poll.h>

#include "serialstd_linux.hpp"
#include "owndebug.h"

//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CSerialStd::CSerialStd()
  : CASRoboBus(),
    iIsOpen(false),
    iPortname(),
    iPortspeed(0),
    iPortfd(-1),
    iOldPortSet(NULL),
    iNewPortSet(NULL)
{
}
//*****************************************************************************

CSerialStd::~CSerialStd()
{
  if ( iOldPortSet ) delete iOldPortSet;
  if ( iNewPortSet ) delete iNewPortSet;

}
//*****************************************************************************

CASRoboBus::EBusStatus CSerialStd::Open(void)
{
  int speed = -1;

  if (iIsOpen == true) {
    dPrint(2,"CSerialStd already open! Will not open again.");
    return KBusStatusNotAvailable;
  }

  iPortfd = open(iPortname.c_str(), O_RDWR | O_SYNC , S_IRUSR | S_IWUSR );
  if (iPortfd < 0) {
    dPrintLE(2,"Failed to open port \"%s\"!",
	   iPortname.c_str());
    return KBusStatusError;
  }

  // Select correct constant variable based on given speed:
  switch(iPortspeed) {
  case 1200:
    speed = B1200;
    dPrint(3,"Selected SerialPort speed 1200");
    break;

  case 9600:
    speed = B9600;
    dPrint(3,"Selected SerialPort speed 9600");
    break;

  case 19200:
    speed = B19200;
    dPrint(3,"Selected SerialPort speed 19200");
    break;

  case 38400:
    speed = B38400;
    dPrint(3,"Selected SerialPort speed 38400");
    break;

  case 57600:
    speed = B57600;
    dPrint(3,"Selected SerialPort speed 57600");
    break;

  case 115200:
    speed = B115200;
    dPrint(3,"Selected SerialPort speed 115200");
    break;
  case 921600:
    speed = B921600;
    dPrint(1,"Selected SerialPort speed 921600");
    break;
  default:
    dPrint(1,"Unsupported serial port speed '%d'!", iPortspeed);
    break;
  }

  if (speed != -1) {
    // Allocate memory
    iOldPortSet = new struct termios;
    iNewPortSet = new struct termios;
    
    // Get old.
    tcgetattr( iPortfd, iOldPortSet);
    
    // Do new.
    if( tcgetattr( iPortfd, iNewPortSet ) < 0 ) {
      dPrint(2, "Failed to read settings for serial port! (%s)",
	     iPortname.c_str());
      return KBusStatusError;
    }
    
    //    cfmakeraw( iNewPortSet );
    // Replaced call to 'cfmakeraw' with following sequence
    // due to platform incompability problems.
    iNewPortSet->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
                            |INLCR|IGNCR|ICRNL|IXON);
    iNewPortSet->c_oflag &= ~OPOST;
    iNewPortSet->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    iNewPortSet->c_cflag &= ~(CSIZE|PARENB);
    iNewPortSet->c_cflag |= CS8;


    
    // Set minimum characters to 2
    iNewPortSet->c_cc[VMIN] = 0; // Minimum 2 chars
    iNewPortSet->c_cc[VTIME] = 5; // Max 5 deciseconds chars
    
    cfsetispeed( iNewPortSet, speed );
    cfsetospeed( iNewPortSet, speed );
    
    if( tcsetattr( iPortfd, TCSAFLUSH,
		   iNewPortSet ) < 0 ) {
      dPrint(2,"Failed to set new settings on serial port! (%s)",
	     iPortname.c_str());
      return KBusStatusError;
    }
    
    tcflush(iPortfd, TCIOFLUSH);
    
    dPrint(4,"Successfully opened Serial device '%s' at speed '%d'", iPortname.c_str(), iPortspeed);
    
  } else {
    dPrint(2,"Failed to open Serial device '%s'", iPortname.c_str());
    return KBusStatusError;

  }
  
  // Got here, so
  iIsOpen = true;

  return KBusStatusOK;
}
//*****************************************************************************

CASRoboBus::EBusStatus CSerialStd::Close(void)
{
  EBusStatus error = KBusStatusError;
  
  if (iIsOpen == true) {
    if((tcsetattr(iPortfd, TCSAFLUSH, iOldPortSet) )!=-1) {
      if((close(iPortfd)) != -1) {
        error = KBusStatusOK;
      }
    }
    iIsOpen = false;
  } else {
    dPrint(2,"Device not open. Cannot Close()");

  }

  return error;
}
//*****************************************************************************

int CSerialStd::Read(unsigned char *buffer, int buffer_size)
{

  int lastread;
  lastread = read(iPortfd, buffer, buffer_size);

  if (lastread < 0) {
    dPrint(3,"Error reading from device! (%s)",
	   iPortname.c_str());
    lastread = -1;
  }

  return lastread;
}
//*****************************************************************************

int CSerialStd::Write(const unsigned char *buffer, int buffer_size)
{
  int wb;

  wb = write(iPortfd, buffer, buffer_size);

  //  tcdrain(iPortfd); // FIXME: Wait until all data transmitted?

  return wb;
}
//*****************************************************************************

CASRoboBus::EBusStatus CSerialStd::WaitToRead(const int aTimeout_ms)
{
  int r;
  struct pollfd p = { iPortfd, POLLIN|POLLERR, 0 };
  EBusStatus status = KBusStatusError;

  // Do poll
  r = poll(&p, 1, aTimeout_ms);

  // Check result
  if (r > 0) {
    // Accept only POLLIN events, other will cause error.
    if (p.revents & POLLIN) {
      status = KBusStatusOK;
    }

  } else if (r == 0) {
    // In case of zero value, assume timeout.
    status = KBusStatusTimeout;

  }
  return status;
}
//*****************************************************************************

CASRoboBus::EBusStatus CSerialStd::WaitToWrite(const int aTimeout_ms)
{
  int r;
  struct pollfd p = { iPortfd, POLLOUT, 0 };
  EBusStatus status = KBusStatusError;

  // Do poll
  r = poll(&p, 1, aTimeout_ms);

  // Check result
  if (r > 0) {
    // Accept only POLLIN events, other will cause error.
    if (p.revents & POLLOUT) {
      status = KBusStatusOK;
    }

  } else if (r == 0) {
    // In case of zero value, assume timeout.
    status = KBusStatusTimeout;

  }

  return status;
}
//*****************************************************************************

int CSerialStd::Flush(void)
{
  int error = -1;

  if (!tcflush(iPortfd, TCIOFLUSH)) {
    error = 0;
  }

  return error;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
